package com.hrm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hrm.mapper.DocumentMapper;
import com.hrm.pojo.DTO.DocumentPageDTO;
import com.hrm.pojo.DTO.DocumentUpdateDTO;
import com.hrm.pojo.Document;
import com.hrm.service.DocumentService;
import com.hrm.utils.JwtUtil;
import com.hrm.utils.entity.PageResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class DocumentServiceImpl implements DocumentService {
    @Autowired
    private DocumentMapper documentMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;

    /**
     * 分页查询
     * @param documentPageDTO
     * @return
     * @throws Exception
     */
    @Override
    public PageResult<Document> selectByTitle(DocumentPageDTO documentPageDTO) throws Exception {
        Page<Document> docPage= PageHelper.startPage(documentPageDTO.getPageNum(),5);
        List<Document> list=documentMapper.selectByTitle(documentPageDTO.getTitle());
        return new PageResult<>(docPage.getTotal(),list);
    }

    /**
     * 删除文档
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public boolean deleteById(Integer id) throws Exception {
        return documentMapper.deleteByPrimaryKey(id)>0;
    }

    /**
     * 修改文档
     * @param documentUpdateDTO
     * @return
     * @throws Exception
     */
    @Override
    public boolean updateDoc(DocumentUpdateDTO documentUpdateDTO) throws Exception {
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtil.parseJWT(token);
        String userId = claims.getId();
        //返回增加数据是否成功
        Document document= new Document();
        document.setUserId(Integer.valueOf(userId));
        BeanUtils.copyProperties(documentUpdateDTO,document);
        return documentMapper.updateByPrimaryKeySelective(document)>0;
    }

    /**
     * 增加文档
     * @param document
     * @return
     * @throws Exception
     */
    @Override
    public boolean addDoc(Document document) throws Exception {
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtil.parseJWT(token);
        String userId = claims.getId();
        //返回增加数据是否成功
        document.setUserId(Integer.valueOf(userId));
        return documentMapper.insertSelective(document)>0;
    }
}
